package logic

import (
	"context"
	configApi "mldong/api/config"
	dao "mldong/internal/modules/sys/dao"
	"mldong/internal/modules/sys/entity"
	service "mldong/internal/modules/sys/service"
	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/jinzhu/copier"
)

func init() {
	// 注册服务实现
	utility.Register(service.ConfigServiceType, NewConfigLogic())
}

type ConfigLogic struct {
	configDao *dao.ConfigDao
}

// 保存配置接口实现
func (logic *ConfigLogic) Save(ctx context.Context, req *configApi.SaveReq) (res bool, err error) {
	unique := utility.CheckUnique(logic.configDao.Model(nil), "code", req.Code, nil, "唯一编码已存在，请检查code参数")
	if unique != nil {
		return false, unique
	}
	var config = entity.Config{}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		req.ID = nil
		// 将req对象赋值给config
		copier.Copy(&config, &req)
		// 插入sys_config表
		config, err = logic.configDao.Insert(config, tx)
		if err != nil {
			return err
		}
		return nil
	})
	utility.InstanceConstantContext().PutConstant(*config.Code, config.Content)
	return config.ID != nil, err
}

// 修改配置接口实现
func (logic *ConfigLogic) Update(ctx context.Context, req *configApi.UpdateReq) (res bool, err error) {
	unique := utility.CheckUnique(logic.configDao.Model(nil), "code", req.Code, req.ID, "唯一编码已存在，请检查code参数")
	if unique != nil {
		return false, unique
	}
	var config = entity.Config{}
	var count int64
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		// 将req对象赋值给config
		copier.Copy(&config, &req)
		count, err = logic.configDao.UpdateById(config, nil)
		return err
	})
	utility.InstanceConstantContext().PutConstant(*config.Code, config.Content)
	return count > 0, err
}

// 删除配置接口实现
func (logic *ConfigLogic) Remove(ctx context.Context, ids []string) (res bool, _ error) {
	// 遍历ids
	// for _, id := range ids {
	// 	logic.configDao.DeleteById(id)
	// }
	var count, err = logic.configDao.DeleteByIds(ids)
	if err != nil {
		return false, err
	}
	if count == 0 {
		return false, err
	}
	// 查询删除的配置信息，
	var configs, erro = logic.configDao.List(func(model *gdb.Model) *gdb.Model {
		model.WhereIn("id", ids)
		return model
	})
	if erro == nil {
		// 遍历configs
		for _, config := range configs {
			// 删除缓存
			utility.InstanceConstantContext().DeleteConstant(*config.Code)
		}
	}
	return true, err
}

// 根据ID获取配置信息
func (logic *ConfigLogic) Detail(ctx context.Context, id string) (res configApi.ConfigVO, err error) {
	var configVO = configApi.ConfigVO{}
	var config entity.Config
	config, err = logic.configDao.GetById(id)

	// 将config对象赋值给configVO
	copier.Copy(&configVO, &config)

	return configVO, err
}

// 分页查询配置接口实现
func (logic *ConfigLogic) Page(ctx context.Context, req *configApi.PageReq) (res configApi.ConfigPageVO, err error) {
	// 处理分页参数nil值
	utility.HandlePageParam(&req.PageParam)
	configs, total, err := logic.configDao.Page(*req.PageNum, *req.PageSize, func(model *gdb.Model) *gdb.Model {
		return utility.BuildQuery(req.PageParam, model)
	})
	var configVOS = []configApi.ConfigVO{}
	copier.Copy(&configVOS, &configs)
	configPage := configApi.ConfigPageVO{
		Rows: configVOS,
	}
	configPage.PageNum = *req.PageNum
	configPage.PageSize = *req.PageSize
	configPage.RecordCount = total
	// 计算 TotalPage
	if *req.PageSize > 0 {
		configPage.TotalPage = (total + *req.PageSize - 1) / *req.PageSize
	} else {
		configPage.TotalPage = 0 // 如果 PageSize 为 0，则 TotalPage 为 0
	}
	return configPage, err
}
func NewConfigLogic() service.IConfigService {
	return &ConfigLogic{
		configDao: dao.NewConfigDao(),
	}
}
